package org.example.rabbitmq.simple;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * @author taritari
 * @date 2023-11-22 15:01
 * @description
 */
public class Producer {
    public static void main(String[] args) {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("****");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        connectionFactory.setVirtualHost("my_vhost");
        Connection connection = null;
        Channel channel = null;
        try {
            connection = connectionFactory.newConnection("生产者");
            channel = connection.createChannel();
            String queueName = "queue1";
            channel.queueDeclare(queueName,false,false,true,null);
            String message = "HelloWorld!";
            channel.basicPublish("",queueName,null,message.getBytes());
            System.out.println("发送成功");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (channel != null && channel.isOpen()){
               try {
                   connection.close();
               }catch (Exception exception){
                   exception.printStackTrace();
               }
            }

            if (connection != null && connection.isOpen()){
                try {
                    connection.close();
                }catch (Exception exception){
                    exception.printStackTrace();
                }
            }
        }
    }
}
